﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MishraReader.Entities.ShareServices
{
    public sealed class InstapaperShareService : ShareServiceBase
    {
        public override bool IsSupported
        {
            get { return true; }
        }
        public InstapaperShareService()
        {
            ServiceName = "Instapaper";
            ServiceId = new Guid("8EF5DCAD-9FFF-4FDE-BED1-FAE9FB0C5B09");
            ServiceType = ServiceType.Bookmark;
        }

        public override bool IsWellConfigured(string userName, string password)
        {
            var url =
                string.Format("https://www.instapaper.com/api/authenticate?username={0}&password={1}", HttpUtility.UrlEncode(userName),
                              HttpUtility.UrlEncode(password));


            var webClient = new WebClient();
            try
            {
                var response = webClient.UploadString(new Uri(url, UriKind.Absolute), "GET");
            }
            catch (WebException)
            {
                return false;
            }
            return true;
        }

        public override void Share(ShareServiceAccount account, string message, Item item)
        {
            var url = string.Format("https://www.instapaper.com/api/add?username={0}&password={1}&url={2}&title={3}",
                                    HttpUtility.UrlEncode(account.UserName), HttpUtility.UrlEncode(account.Password),
                                    HttpUtility.UrlEncode(item.PostUri.ToString()), HttpUtility.UrlEncode(item.Title));

            var webClient = new WebClient();
            webClient.UploadString(new Uri(url, UriKind.Absolute), "GET");
        }
    }
}